var express = require('express');
var jwt = require('jwt-simple');
var app = express();
app.set('jwtTokenSecret', 'booking');

var moment = require('moment');

exports.getSetting=function(key){
	if(key==null||key=="")return "";
	if(key=="apisite") return "http://localhost:3000/files/images/yeyu.jpg";
}


exports.getResult = function (obj,defautValue) {
	var result=obj;
	if(obj==undefined||obj==null){ 
	  return defautValue;	
	}else return result;
};


/*
type:md5,md4,sha1
*/
exports.encrypt = function (pwd,type) {
	var crypto = require('crypto');  
	var r = crypto.createHash(type);//定义加密方式:md5不可逆,此处的md5可以换成任意hash加密的方法名称；
    r.update(pwd);
    return r.digest('hex');    
};



//Token 创建
exports.jwtCreateToken = function (code) {
	var expires = moment().add(7, 'days').format('YYYY-MM-DD HH:mm:ss');
	var token = jwt.encode({
	  code: code,
	  exp: expires
	}, app.get('jwtTokenSecret'));
	return token;
};


//验证token是否失效(true:token有效，false：token过期)
exports.tokenValid = function (token) {
	try{
		if(token=="signout"||token=="")return false;
	    var decoded = jwt.decode(token, app.get('jwtTokenSecret'));
	    console.log(decoded.exp);
	    return !moment().isAfter(decoded.exp);	
	}
	catch(ex){
		return false;
	}	
}

//操作前控制token有效性
exports.verifyToken=function(req,res,user,next){
	console.log("verifySign");
	var token=exports.getResult(req.query.token,"");
	if(token=="") return res.json({ result: false,messageflag:'token_required',message:"The token is required." }); 
	if(!exports.tokenValid(token))  return res.json({ result: false,messageflag:'token_invalid',message:"The token is Invalid." }); 
	else{
		var resultObj = user.findOne({ "token": token,"status":"active"},'-_id token', function (err, result) {
        if (err) return res.json({ result: false,messageflag:'error',message:"error."});
        else if (result!=null) next();
        else return res.json({ result: false,messageflag:'token_invalid',message:"The token is Invalid." }); 
       });
	}
}